package com.huike.pmps.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huike.pmps.dao.PersonnelCostDao;
import com.huike.pmps.model.constants.GlobalConstants;
import com.huike.pmps.model.dto.common.PageInfo;
import com.huike.pmps.model.entity.PersonnelCost;
import com.huike.pmps.model.entity.Provinces;
import com.huike.pmps.model.entity.Region;
import com.huike.pmps.model.vo.PageResult;
import com.huike.pmps.model.vo.Result;
import com.huike.pmps.service.PersonnelCostService;
import com.huike.pmps.service.ProvincesService;
import com.huike.pmps.service.RegionService;
import com.huike.pmps.utils.PmpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 作者：谌贵斌(黑桃K)
 * 日期: 2888-08-08
 * 老师QQ: 272488352
 * 官方QQ交流群: 377748272
 * 刀客程序员官网：http://www.daoke360.com
 * 刀客程序员淘宝旗舰店：https://daoke360.taobao.com/
 */
@Service
@Slf4j
public class PersonnelCostServiceImpl implements PersonnelCostService {
    @Autowired
    RegionService regionService;
    @Autowired
    ProvincesService provincesService;
    @Autowired
    PersonnelCostDao personnelCostDao;

    @Override
    public Result insertByImportPersonnelCost(MultipartFile file) {
        if (file.isEmpty()) {
            return Result.failure("文件为空");
        }
        try {
            //根据路径获取这个操作excel的实例
            XSSFWorkbook wb = new XSSFWorkbook(file.getInputStream());
            //根据页面index 获取sheet页
            XSSFSheet sheet = wb.getSheetAt(0);
            //获取标题行
            XSSFRow titleRow = sheet.getRow(0);
            XSSFRow row = null;
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy.M");
            List<PersonnelCost> personnelCostList = new ArrayList<>();
            for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
                //获取每一行数据
                row = sheet.getRow(i);

                if (row.getCell(1) == null || StringUtils.isBlank(row.getCell(1).toString()))
                    return Result.success("第" + i + "条数据,工号为空，本次导入全部失败");

                if (row.getCell(1).toString().contains("VLOOKUP"))
                    return Result.success("表格中不允许含有公式，本次导入全部失败");

                if (row.getCell(2) == null || StringUtils.isBlank(row.getCell(2).toString()))
                    return Result.success("第" + i + "条数据,课程顾问为空，本次导入全部失败");

                Integer regionId, provinceId = null;
                String regionName, provinceName = null;
                if (row.getCell(3) == null || StringUtils.isBlank(row.getCell(3).toString())) {
                    return Result.success("第" + i + "条数据,省份为空，本次导入全部失败");
                } else {
                    Provinces provinces = provincesService.selectByProvinceName(row.getCell(3).toString());
                    if (provinces != null) {
                        provinceId = provinces.getProvinceId();
                        provinceName = provinces.getProvince();
                    } else {
                        return Result.success("第" + i + "条数据,省份数据填写有误,请按规则填写");
                    }
                }
                if (row.getCell(4) == null || StringUtils.isBlank(row.getCell(4).toString())) {
                    return Result.success("第" + i + "条数据,战区为空，本次导入全部失败");
                } else {
                    Region region = regionService.selectOneByRegionName(row.getCell(4).toString());
                    if (region != null) {
                        regionId = region.getId();
                        regionName = region.getRegion();
                    } else {
                        return Result.success("第" + i + "条数据,战区数据填写有误,请按规则填写");
                    }
                }

                for (int j = 5; j < titleRow.getPhysicalNumberOfCells(); j++) {
                    XSSFCell salaryCell = row.getCell(j);

                    if (salaryCell != null && StringUtils.isNotBlank(salaryCell.toString())) {

                        //工号	课程顾问	省份	战区	2020.1	2020.2	2020.3	2020.4	2020.5	2020.6	2020.7
                        PersonnelCost personnelCost = new PersonnelCost();
                        personnelCost.setJobNumber(row.getCell(1).toString());
                        personnelCost.setCourseChargeName(row.getCell(2).toString());
                        personnelCost.setRegionId(regionId);
                        personnelCost.setRegionName(regionName);
                        personnelCost.setProvinceId(provinceId);
                        personnelCost.setProvinceName(provinceName);
                        personnelCost.setSalary(BigDecimal.valueOf(Double.valueOf(salaryCell.toString())));

                        Date ym = simpleDateFormat.parse(titleRow.getCell(j).toString());
                        Calendar calendar = simpleDateFormat.getCalendar();
                        calendar.setTime(ym);
                        personnelCost.setYear(calendar.get(Calendar.YEAR));
                        personnelCost.setMonth(calendar.get(Calendar.MONTH) + 1);
                        personnelCost.setYearMonthStr(titleRow.getCell(j).toString());
                        personnelCost.setYearMonthDate(ym);
                        personnelCost.setWeekOfYear(PmpUtil.getDateInfo(ym, GlobalConstants.WEEK_OF_YEAR));
                        personnelCost.setSeasonOfYear(PmpUtil.getDateInfo(ym, GlobalConstants.SEASON));
                        personnelCost.setMonthOfYear(PmpUtil.getDateInfo(ym, GlobalConstants.MONTH));
                        personnelCost.setCreateTime(new Date());

                        QueryWrapper<PersonnelCost> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("job_number", personnelCost.getJobNumber());
                        queryWrapper.eq("year_month_str", personnelCost.getYearMonthStr());
                        PersonnelCost one = personnelCostDao.selectOne(queryWrapper);
                        if (one != null)
                            personnelCost.setId(one.getId());
                        personnelCostList.add(personnelCost);
                    }
                }
            }

            if (personnelCostList.size() > 0) {
                for (PersonnelCost personnelCost : personnelCostList) {
                    if (personnelCost.getId() != null) {
                        personnelCostDao.updateById(personnelCost);
                    } else {
                        personnelCostDao.insert(personnelCost);
                    }
                }
                return Result.success();
            } else {
                return Result.failure("表格中没有数据");
            }
        } catch (ParseException e) {
            log.error(e.getMessage());
            return Result.failure("导入失败，请检查标题行相关日期格式是否符合：yyyy.M  格式要求");
        } catch (IOException e) {
            log.error(e.getMessage());
            return Result.failure("导入失败，读取表格数据异常" + e.getMessage());
        }
    }

    @Override
    public Result selectByCondition(PageInfo pageInfo, Integer regionId, Integer provinceId, String courseChargeName, Integer year, Integer month) {
        QueryWrapper<PersonnelCost> queryWrapper = new QueryWrapper<>();
        if (regionId != null)
            queryWrapper.eq("region_id", regionId);
        if (provinceId != null)
            queryWrapper.eq("province_id", provinceId);
        if (StringUtils.isNotBlank(courseChargeName))
            queryWrapper.like("course_charge_name", courseChargeName);
        if (year != null)
            queryWrapper.eq("year", year);
        if (month != null)
            queryWrapper.eq("month", month);
        Page<PersonnelCost> page = new Page<>(pageInfo.getPage(), pageInfo.getPageSize());
        Page<PersonnelCost> pageList = personnelCostDao.selectPage(page, queryWrapper);
        if (pageList.getSize() > 0) {
            PageResult pageResult = PageResult.builder().pageNumber(pageList.getCurrent()).pageSize(pageList.getSize())
                    .total(pageList.getTotal()).rows(pageList.getRecords()).build();
            return Result.success(pageResult);
        } else {
            return Result.success("没有符合条件的记录");
        }
    }
}
